package com.cqeec.gams.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cqeec.gams.entity.Account;
import com.cqeec.gams.entity.FunctionalModule;
import com.cqeec.gams.mapper.AccountMapper;
import com.cqeec.gams.mapper.FunctionalModuleMapper;
import com.cqeec.gams.model.Function;

@Service
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private FunctionalModuleMapper functionalModuleMapper;

	@Override
	public Account login(String name, String password) {
		return accountMapper.findLoginAccount(name, password);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.cqeec.gams.service.AccountService#checkUserPassword(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public boolean checkUserPassword(String id, String oldPassword) {
		int count = accountMapper.countByIdAndPassword(id, oldPassword);
		return count == 1 ? true : false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.cqeec.gams.service.AccountService#updatePassword(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public void updatePassword(String id, String newPassword) {
		accountMapper.updatePassword(id, newPassword);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.cqeec.gams.service.AccountService#getUserFunction(java.lang.String)
	 */
	@Override
	public List<FunctionalModule> getUserFunctionalModule(String id) {
		return functionalModuleMapper.findUserFunction(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.cqeec.gams.service.AccountService#getUserFunction(com.cqeec.gams.entity.
	 * Account)
	 */
	@Override
	public List<Function> getUserFunction(String id) {
		List<FunctionalModule> list = this.getUserFunctionalModule(id);
		List<Function> functionList = new ArrayList<>();
		// 读取功能组
		Function fun;
		Map<String, List<FunctionalModule>> map = new HashMap<String, List<FunctionalModule>>();
		for (FunctionalModule fm : list) {
			if (fm.getParent() == null) {
				fun = new Function();
				fun.setId(fm.getId());
				fun.setName(fm.getName());
				functionList.add(fun);
				map.put(fm.getId(), new ArrayList<FunctionalModule>());
			}
		}
		// 读取功能组的功能模块
		String parent;
		List<FunctionalModule> temp;
		for (FunctionalModule fm : list) {
			parent = fm.getParent();
			if (parent != null && map.containsKey(parent)) {
				temp = map.get(parent);
				temp.add(fm);
			}
		}
		// 将功能模块放到列表中
		Set<String> key = map.keySet();
		for (String k : key) {
			for (Function f : functionList) {
				if (f.getId().equals(k)) {
					f.setFunctionalModule(map.get(k));
				}
			}
		}
		return functionList;
	}

}
